﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CNSpider
{
    public partial class FormMain : Form
    {
        public FormMain()
        {
            InitializeComponent();
        }

        private void FormMain_Load(object sender, EventArgs e)
        {
            Debugger.myForm = this;
            Debugger.buffer = textBoxDebugBuffer;
            RefreshProperties();

            // Add some default urls.
            AddNewEntryURL("http://www.cppblog.com/");
            AddNewEntryURL("http://mindhacks.cn/");
            AddNewEntryURL("http://mindhacks.cn/topics/programming/");
        }

        private void RefreshProperties()
        {
            if (textBoxStorePath.Text.Length > 0)
            {
                Spider.StoreFilePath = textBoxStorePath.Text;
            }
            if (textBoxFilePrefix.Text.Length > 0)
            {
                Spider.FilePrefix = textBoxFilePrefix.Text;
            }
            if (textBoxContentPattern.Text.Length > 0)
            {
                Spider.ContentPattern = textBoxContentPattern.Text;
            }
        }

        static private List<string> _entryURLs = new List<string>();
        private void AddNewEntryURL(string url)
        {
            if (url.Length == 0)
            {
                return;
            }
            if (!url.Contains("http://") && !url.Contains("https://"))
            {
                url = "http://" + url;
            }
            lock (_entryURLs)
            {
                _entryURLs.Add(url);
            }
            textBoxShowURL.AppendText(url + "\n");
            textBoxNewURL.Clear();
        }

        private void buttonAddURL_Click(object sender, EventArgs e)
        {
            AddNewEntryURL(textBoxNewURL.Text);
        }

        private void textBoxNewURL_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                AddNewEntryURL(textBoxNewURL.Text);
            }
        }

        private void buttonRunSpider_Click(object sender, EventArgs e)
        {
            RefreshProperties();
            foreach (string url in _entryURLs)
            {
                Spider.AddURL(url);
            }

            for (int i = 0; i < 4; i++)
            {
                Spider spider = new Spider();
                ThreadPool.QueueUserWorkItem((async =>
                {
                    spider.RunSpider();
                }), null);
            }
        }
    }
}
